package com.loveazure.ui;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

import javax.swing.BoundedRangeModel;
import javax.swing.JOptionPane;

import com.loveazure.bll.Handler;
import com.loveazure.eo.Course;
import com.loveazure.util.FileUtil;

public class ImportThread extends Thread {
	private File file;
	private BoundedRangeModel model;
	private int importNumber = 0;
	private String courseName;
	private CourseImportDialog dialog;

	public ImportThread(File file, String courseName, BoundedRangeModel model,
			CourseImportDialog dialog) {
		this.file = file;
		this.model = model;
		this.courseName = courseName;
		this.dialog = dialog;
	}

	@Override
	public void run() {
		model.setMaximum(FileUtil.countLine(file));

		ArrayList<String> list = new ArrayList<String>();
		File tempFile;
		try {
			FileInputStream fis = new FileInputStream(file);
			InputStreamReader isr = new InputStreamReader(fis, FileUtil
					.getCharset(file));
			BufferedReader reader = new BufferedReader(isr);

			String line;
			while (reader.ready()) {
				line = reader.readLine();
				if (line.matches("[^a-zA-Z '-]+")) {
					// if (WebDict.checkWord(line)) {
					list.add(line);
					importNumber++;
				}
				model.setValue(model.getValue() + 1);
			}
			reader.close();

			StringBuffer sb = new StringBuffer();
			for (String s : list) {
				sb.append(s).append("\n");
			}

			String fileName = "" + System.currentTimeMillis();

			File folder = new File("words");
			folder.mkdirs();

			tempFile = new File(folder, fileName);
			tempFile.createNewFile();
			FileOutputStream fos = new FileOutputStream(tempFile);
			OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
			osw.write(sb.toString());
			osw.flush();
			osw.close();
			dialog.setCourse(Handler.getInstance().getOper().processImportFile(
					tempFile, courseName));
			dialog.dispose();
			JOptionPane.showMessageDialog(null, "已导入" + importNumber + "个单词");

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
